package mmail;
import java.util.Scanner;

public class MailList implements IList {

    static Scanner sc=new Scanner(System.in);
    public Node head;
    public int size;
    int maxSize = 1000;


    public MailList(){
        this.head = new Node();
    }//初始化了一个空的头节点

    //添加联系人
    public void addPerson(){
        if (size >= maxSize){
            System.out.println("通讯录已满，无法添加！");
        }
        else {
            System.out.println("请输入您要添加的联系人姓名：");
            String name = sc.next();
            System.out.println("请输入您要添加的联系人电话：");
            String phone = sc.next();
            System.out.println("请输入您要添加的联系人单位：");
            String danwei = sc.next();
            Person person = new Person(name,phone,danwei);
            Node node = new Node(person);
            size++;

            Node p = this.head;
            while(p.next != null){
                p = p.next;
            }
            p.next = node;
        }
    }


    public Person get(int i) {
        Node p = head.next;
        int j = 0;
        while (p!=null && j<i){
            p = p.next;
            ++j;
        }
        return p.person;
    }


    public int indexOf(String name){
        Node p = head.next;
        int j = 0;
        while (p!=null && !p.person.name.equals(name)){
            p = p.next;
            ++j;
        }
        if (p!=null){
            return j;
        }
        else return -1;
    }

    //删除联系人
    public void deletePerson(){
        System.out.println("请输入您要删除的联系人姓名：");
        String name = sc.next();
        int ret = indexOf(name);
        if (ret != -1){
            Node p = head;
            int j = -1;
            while (p.next!=null && j<ret-1){
                p = p.next;
                ++j;
            }
            p.next = p.next.next;
            System.out.println("删除成功！");
            size--;
        }
        else {
            System.out.println("您要删除的联系人不存在！");
        }
    }




    public void findPerson(){
        System.out.println("请输入您要查找的联系人姓名：");
        String name = sc.next();
        int ret = indexOf(name);
        if (ret != -1){
            System.out.print("姓名："+get(ret).name+"\t");
            System.out.println("电话："+get(ret).phone);
            System.out.println("单位："+get(ret).danwei);
        }
        else {
            System.out.println("您要查找的联系人不存在！");
        }

    }


    public void showPerson(){
        if (size == 0){
            System.out.println("当前通讯录为空！");
        }
        else {
            Node p = this.head.next;
            while (p != null){
                System.out.print("姓名："+p.person.name+"\t");
                System.out.println("电话："+p.person.phone);
                System.out.println("单位："+p.person.danwei);
                p = p.next;
            }
        }
    }




}



